package com.jianan.mis.app.basedata;

import static com.jianan.mis.util.ui.calendar.SWTCalendarWrapper.openCalendar;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;

import com.jianan.mis.data.domain.Employee;
import com.jianan.mis.data.domain.Interman;
import com.jianan.mis.data.domain.InternalOrganization;
import com.jianan.mis.data.domain.Session;
import com.jianan.mis.service.EmployeeService;
import com.jianan.mis.service.IntermanService;
import com.jianan.mis.service.InternalOrganizationService;
import com.jianan.mis.sys.IGroupKeys;
import com.jianan.mis.sys.IMessageKeys;
import com.jianan.mis.sys.SpringBeanFactory;
import com.jianan.mis.util.StringUtils;

@SuppressWarnings("unchecked")
public class IntermanView extends ViewPart {
	private Combo internalOrganizationCombo;
	class ContentProvider implements IStructuredContentProvider {
		public Object[] getElements(Object inputElement) {
			return ((List) inputElement).toArray();
		}
		public void dispose() {
		}
		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
		}
	}
	class IntermanListLabelProvider extends LabelProvider {
		public String getText(Object element) {
			Interman interman = (Interman) element;
			return interman.getName();
		}
		public Image getImage(Object element) {
			return null;
		}
	}
	class EmployeeListLabelProvider extends LabelProvider {
		public String getText(Object element) {
			Employee employee = (Employee) element;
			return employee.getName();
		}
		public Image getImage(Object element) {
			return null;
		}
	}

	class InternalOrgnizationListLabelProvider extends LabelProvider {
		public String getText(Object element) {
			InternalOrganization internalOrganization = (InternalOrganization) element;
			return internalOrganization.getName();
		}
		public Image getImage(Object element) {
			return null;
		}
	}
	private ComboViewer intermanComboViewer;
	private Combo intermanCombo;
	private Combo employeeCombo;
	private Text txtAddress;
	private Text txtPhone;
	private Text txtBirthday;
	private Text txtName;
	private ComboViewer employeeComboViewer;
	private ComboViewer internalOrganizationComboViewer;
	public static final String ID = "com.jianan.mis.app.basedata.IntermanView"; //$NON-NLS-1$

	final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM月dd日");
	
	private EmployeeService employeeService;
	
	private InternalOrganizationService internalOrganizationService;
	
	private IntermanService intermanService;
	
	private Interman currentInterman;

	/**
	 * Create contents of the view part
	 * @param parent
	 */
	@Override
	public void createPartControl(Composite parent) {
		
		if(!initializeServices()) {
			MessageDialog.openError(getViewSite().getShell(),
					IMessageKeys.OPEN_VIEW_FAIL, IMessageKeys.SERVICE_UNAVAILABLE);
			return;
		}
		
		Composite container = new Composite(parent, SWT.NONE);
		final GridLayout gridLayout = new GridLayout();
		gridLayout.makeColumnsEqualWidth = true;
		gridLayout.numColumns = 3;
		container.setLayout(gridLayout);

		final Label label = new Label(container, SWT.NONE);
		label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false));
		label.setText("选择中间人:");

		intermanComboViewer = new ComboViewer(container, SWT.READ_ONLY);
		intermanComboViewer.addSelectionChangedListener(new ISelectionChangedListener() {
			public void selectionChanged(final SelectionChangedEvent event) {
				IStructuredSelection selection = (IStructuredSelection) event.getSelection();
				currentInterman = (Interman) selection.getFirstElement();
				txtName.setText(currentInterman.getName());
				if (currentInterman.getBirthday() != null)
					txtBirthday.setText(simpleDateFormat.format(currentInterman.getBirthday()));
				if (currentInterman.getPhone() != null)
					txtPhone.setText(currentInterman.getPhone());
				if (currentInterman.getAddress() != null)
					txtAddress.setText(currentInterman.getAddress());
				
				if (currentInterman.getEmployee() != null && employeeComboViewer.getInput() != null) {
					List<Employee> employees = (List<Employee>) employeeComboViewer.getInput();
					for (int i = 0; i < employees.size(); i++) {
						Employee employee = employees.get(i);
						if (employee.getId().equals(currentInterman.getEmployee().getId())) {
							employeeCombo.select(i);
						}
					}
				}
				
				if (currentInterman.getInternalOrganization() != null && internalOrganizationComboViewer.getInput() != null) {
					List<InternalOrganization> organizations = (List<InternalOrganization>) internalOrganizationComboViewer.getInput();
					for (int i = 0; i < organizations.size(); i++) {
						InternalOrganization organization = organizations.get(i);
						if (organization.getId().equals(currentInterman.getInternalOrganization().getId())) {
							internalOrganizationCombo.select(i);
						}
					}
				}
			}
		});
		intermanComboViewer.setContentProvider(new ContentProvider());
		intermanComboViewer.setLabelProvider(new IntermanListLabelProvider());
		intermanCombo = intermanComboViewer.getCombo();
		final GridData gd_combo = new GridData(SWT.LEFT, SWT.CENTER, true, false, 2, 1);
		gd_combo.widthHint = 45;
		intermanCombo.setLayoutData(gd_combo);
		setTableViewer();

		final Label label_1 = new Label(container, SWT.NONE);
		label_1.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false));
		label_1.setText("姓名:");

		txtName = new Text(container, SWT.BORDER);
		final GridData gd_txtName = new GridData(SWT.LEFT, SWT.CENTER, true, false, 2, 1);
		txtName.setLayoutData(gd_txtName);

		final Label label_2 = new Label(container, SWT.NONE);
		label_2.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false));
		label_2.setText("生日:");

		txtBirthday = new Text(container, SWT.BORDER);
		txtBirthday.setEditable(false);
		txtBirthday.addMouseListener(new MouseAdapter() {
			public void mouseDown(final MouseEvent e) {
				openCalendar(e, txtBirthday, simpleDateFormat);
			}
		});
		final GridData gd_txtBirthday = new GridData(SWT.LEFT, SWT.CENTER, true, false, 2, 1);
		gd_txtBirthday.widthHint = 102;
		txtBirthday.setLayoutData(gd_txtBirthday);

		final Label label_3 = new Label(container, SWT.NONE);
		label_3.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false));
		label_3.setText("联系电话:");

		txtPhone = new Text(container, SWT.BORDER);
		final GridData gd_txtPhone = new GridData(SWT.LEFT, SWT.CENTER, true, false, 2, 1);
		gd_txtPhone.widthHint = 131;
		txtPhone.setLayoutData(gd_txtPhone);

		final Label label_4 = new Label(container, SWT.NONE);
		label_4.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false));
		label_4.setText("联系地址:");

		txtAddress = new Text(container, SWT.BORDER);
		final GridData gd_txtAddress = new GridData(SWT.LEFT, SWT.CENTER, true, false, 2, 1);
		gd_txtAddress.widthHint = 329;
		txtAddress.setLayoutData(gd_txtAddress);

		final Label label_5 = new Label(container, SWT.NONE);
		label_5.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false));
		label_5.setText("选择关系员工:");

		employeeComboViewer = new ComboViewer(container, SWT.BORDER);
		employeeComboViewer.setLabelProvider(new EmployeeListLabelProvider());
		employeeComboViewer.setContentProvider(new ContentProvider());
		employeeCombo = employeeComboViewer.getCombo();
		final GridData gd_combo_1 = new GridData(SWT.LEFT, SWT.CENTER, true, false, 2, 1);
		gd_combo_1.widthHint = 65;
		employeeCombo.setLayoutData(gd_combo_1);
		employeeComboViewer.setInput(employeeService.getAll());

		final Label label_6 = new Label(container, SWT.NONE);
		label_6.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_6.setText("选择对内合作机构:");

		internalOrganizationComboViewer = new ComboViewer(container, SWT.BORDER);
		internalOrganizationComboViewer.setLabelProvider(new InternalOrgnizationListLabelProvider());
		internalOrganizationComboViewer.setContentProvider(new ContentProvider());
		internalOrganizationCombo = internalOrganizationComboViewer.getCombo();
		internalOrganizationCombo.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false));
		internalOrganizationComboViewer.setInput(internalOrganizationService.getAll());
		new Label(container, SWT.NONE);

		final Button btnSave = new Button(container, SWT.NONE);
		btnSave.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				if (checkInfo()) {
					Interman interman = new Interman();
					fillIntermanFields(interman);
					try {
						intermanService.save(interman);
						reset();
						MessageDialog.openInformation(e.display.getActiveShell(), 
								IMessageKeys.SUCCESS, "新增中间人信息成功!");
					} catch(Exception ex) {
						MessageDialog.openError(e.display.getActiveShell(),
								IMessageKeys.FAIL, ex.getMessage());
						return;
					}
				}
			}
		});
		final GridData gd_btnSave = new GridData(SWT.RIGHT, SWT.CENTER, false, false);
		btnSave.setLayoutData(gd_btnSave);
		btnSave.setText("添加中间人");

		final Button btnUpdate = new Button(container, SWT.NONE);
		btnUpdate.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				if(currentInterman == null) {
					MessageDialog.openInformation(e.display.getActiveShell(), 
							IMessageKeys.FAIL, "请选择一个中间人!");
					return;
				}
				if (checkInfo()) {
					fillIntermanFields(currentInterman);
					try {
						intermanService.update(currentInterman);
						reset();
						MessageDialog.openInformation(e.display.getActiveShell(), 
								IMessageKeys.SUCCESS, "更新中间人信息成功!");
					} catch(Exception ex) {
						MessageDialog.openError(e.display.getActiveShell(),
								IMessageKeys.FAIL, ex.getMessage());
						return;
					}
				}
			}
		});
		final GridData gd_btnUpdate = new GridData(SWT.CENTER, SWT.CENTER, false, false);
		btnUpdate.setLayoutData(gd_btnUpdate);
		btnUpdate.setText("更新中间人");

		final Button btnRemove = new Button(container, SWT.NONE);
		btnRemove.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				if(currentInterman == null) {
					MessageDialog.openInformation(e.display.getActiveShell(), 
							IMessageKeys.FAIL, "请选择一个中间人!");
					return;
				}
				if(MessageDialog.openConfirm(e.display.getActiveShell(), 
						IMessageKeys.CONFIRM, "确认删除该中间人吗?")) {
					try {
						intermanService.remove(currentInterman);
						reset();
						MessageDialog.openInformation(e.display.getActiveShell(), 
								IMessageKeys.SUCCESS, "删除中间人信息成功!");
					} catch(Exception ex) {
						MessageDialog.openError(e.display.getActiveShell(),
								IMessageKeys.FAIL, ex.getMessage());
					}
				}
			}
		});
		btnRemove.setText("删除中间人");
		
		if (Session.getInstance().getGroups().contains(IGroupKeys.MANAGER)) {
			btnRemove.setEnabled(true);
		} else {
			btnRemove.setEnabled(false);
		}
		
		//
		createActions();
		initializeToolBar();
		initializeMenu();
	}
	
	private boolean initializeServices() {
		employeeService = (EmployeeService) SpringBeanFactory.getBean("employeeService");
		if(employeeService == null) {
			return false;
		}
		internalOrganizationService = (InternalOrganizationService) SpringBeanFactory.getBean("internalOrganizationService");
		if(internalOrganizationService == null) {
			return false;
		}
		intermanService = (IntermanService) SpringBeanFactory.getBean("intermanService");
		if(intermanService == null) {
			return false;
		}
		return true;
	}
	
	private void setTableViewer() {
		if (Session.getInstance().getGroups().contains(IGroupKeys.MANAGER)) {
			intermanComboViewer.setInput(intermanService.getAll());
		} else {
			intermanComboViewer.setInput(intermanService
					.getAllByEmployeeId(Session.getInstance().getEmployeeId()));
		}
	}
	
	private void reset() {
		txtName.setText("");
		txtBirthday.setText("");
		txtPhone.setText("");
		txtAddress.setText("");
		employeeComboViewer.setSelection(null);
		internalOrganizationComboViewer.setSelection(null);
		currentInterman = null;
		setTableViewer();
	}
	
	private void fillIntermanFields(Interman interman) {
		interman.setName(txtName.getText());
		if (StringUtils.isNotEmpty(txtBirthday.getText())) {
			try {
				interman.setBirthday(simpleDateFormat.parse(txtBirthday.getText()));
			} catch (ParseException ex) {
				ex.printStackTrace();
			}
		} else {
			interman.setBirthday(null);
		}
		if (StringUtils.isNotEmpty(txtPhone.getText()))
			interman.setPhone(txtPhone.getText());
		else
			interman.setPhone(null);
		if (StringUtils.isNotEmpty(txtAddress.getText()))
			interman.setAddress(txtAddress.getText());
		else
			interman.setAddress(null);
		if(employeeComboViewer.getSelection() != null) {
			IStructuredSelection selection = (IStructuredSelection) employeeComboViewer.getSelection();
			Employee employee = (Employee) selection.getFirstElement();
			interman.setEmployee(employee);
		}
		if(internalOrganizationComboViewer.getSelection() != null) {
			IStructuredSelection selection = (IStructuredSelection) internalOrganizationComboViewer.getSelection();
			InternalOrganization organization = (InternalOrganization) selection.getFirstElement();
			interman.setInternalOrganization(organization);
		}
	}
	
	private boolean checkInfo() {
		if(StringUtils.isEmpty(txtName.getText())) {
			MessageDialog.openError(getViewSite().getWorkbenchWindow().getShell(), 
					IMessageKeys.INFORMATION, "请输入中间人姓名!");
			return false;
		}
		return true;
	}

	/**
	 * Create the actions
	 */
	private void createActions() {
		// Create the actions
	}

	/**
	 * Initialize the toolbar
	 */
	private void initializeToolBar() {
	}

	/**
	 * Initialize the menu
	 */
	private void initializeMenu() {
	}

	@Override
	public void setFocus() {
		// Set the focus
	}

}
